package com.liao.domain.strategy.service.rule.chain.impl;

import com.liao.domain.strategy.model.entity.RuleActionEntity;
import com.liao.domain.strategy.model.valobj.RuleLogicCheckTypeVO;
import com.liao.domain.strategy.repository.IStrategyRepository;
import com.liao.domain.strategy.service.armory.IStrategyDispatch;
import com.liao.domain.strategy.service.rule.chain.AbstractLogicChain;
import com.liao.domain.strategy.service.rule.chain.factory.DefaultChainFactory;
import com.liao.types.common.Constants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.*;

/**
 * @Author long
 * @Description 权重规则
 * @Date 2024-08-26 11:38
 */
@Slf4j
@Component("rule_weight")
public class RuleWeightLogicChain extends AbstractLogicChain {
    @Resource
    private IStrategyRepository strategyRepository;
    @Resource
    private IStrategyDispatch strategyDispatch;

    //模拟抽奖次数
    private Long userScore = 4500L;

    @Override
    public DefaultChainFactory.StrategyAwardVO logic(String userId, Long strategyId) {
        log.info("抽奖责任链-权重开始 userId: {} strategyId: {} ruleModel: {}", userId, strategyId, ruleModel());
        //4000:102,103,104 5000:102,103,104,105,106 6000:102,103,104,105,106,107,108,109
        //获取黑权重的规则 数据结构：消耗积分:奖品ID1,奖品ID2,奖品ID3
        String ruleValue = strategyRepository.queryStrategyRuleValue(strategyId, ruleModel());
        Map<Long, String> analyticalValueGroup = getAnalyticalValue(ruleValue);
        if (analyticalValueGroup == null || analyticalValueGroup.isEmpty()) {
            return super.next().logic(userId, strategyId);
        }
        List<Long> userScoreList = new ArrayList<>(analyticalValueGroup.keySet());
        Collections.sort(userScoreList);

        Long preUserScore = null;
        for (Long l : userScoreList) {
            if (l <= userScore) {
                preUserScore = l;
            } else {
                break;
            }
        }
        if (preUserScore != null) {
            Long awardId = strategyDispatch.getRandomAwardId(strategyId, analyticalValueGroup.get(preUserScore));
            log.info("抽奖责任链-权重接管 userId: {} strategyId: {} ruleModel: {} awardId: {}", userId, strategyId, ruleModel(), awardId);
            return DefaultChainFactory.StrategyAwardVO.builder()
                    .awardId(awardId)
                    .logicModel(ruleModel())
                    .build();
        }

        //没有达到规定的最低积分，奖品的范围是全部奖品，随着积分消耗的增加，不同阶段对用的奖品不同
        log.info("抽奖责任链-权重放行 userId: {} strategyId: {} ruleModel: {}", userId, strategyId, ruleModel());
        return super.next().logic(userId, strategyId);

    }

    private Map<Long, String> getAnalyticalValue(String ruleValue) {
        String[] ruleValueGroups = ruleValue.split(Constants.SPACE);
        Map<Long, String> ruleValueMap = new HashMap<>();
        for (String ruleValueKey : ruleValueGroups) {
            // 检查输入是否为空
            if (ruleValueKey == null || ruleValueKey.isEmpty()) {
                return ruleValueMap;
            }
            // 分割字符串以获取键和值
            String[] parts = ruleValueKey.split(Constants.COLON);
            if (parts.length != 2) {
                throw new IllegalArgumentException("rule_weight rule_rule invalid input format" + ruleValueKey);
            }
            ruleValueMap.put(Long.parseLong(parts[0]), ruleValueKey);
        }
        return ruleValueMap;
    }

    @Override
    protected String ruleModel() {
        return DefaultChainFactory.LogicModel.RULE_WEIGHT.getCode();
    }
}
